TWO SCOOPS OF DJANGO

キーフレーズ

and Django the for django that are with you this EXAMPLE from code Python project can http:// your python import model more https ing use models ice cream have views get chapter () request class like but them should settings template other method For about will when example form projects data using follow When our test return org make the c need with t object not one com database based used which JavaScript has create Use any they view forms to function http pypi user lhis core just dj a server lhe production You name With ngo base very into modets self def API

目次

Contents D edication About the Dedication . A Ⅱ市 0 Notes A Few Words From DanieI Roy Greenfeld A Few Words From Audrey Roy Greenfeld lntroduction A Word About Our Recommendations Why Two Scoops ofDjango? Before You Begin lhis book is intended for Django 1.8 and Python 2.7. ツ 3.3.3 + . Each Chapter Stands On lts Own Conventions Used in lhis Book . Core Concepts Keep lt SimpIe, Stupid Fat ModeIs, UtiIity ModuIes, lhin Views, Stupid Templates Start With Django By DefauIt Be Fami1iar with Django's Design PhiIosophies 'lhe TweIve-Factor App Our Writing Concepts Provide the Best Material Stand on the Shoulders of Giants . Listen tO O ur Readers and Revie 、 vers Publish Errata . 1 Coding Sty1e 1.1 lhe lmportance ofMaking Your Code Readable Ⅵ 1 1

Co 〃〃な つんっ 0 っ 0 -4 冖 / ′ . -0 0 0 1 亠 11 っ 1 1 1 1 1 1 1.2 PEP 8 1.2.1 %e 79-Character Limit . 1.3 FIhe 、 vord on lmports 1.4 Use ExpIicit ReIative lmports 1.5 Avoid Using lmport 1.6 Django Coding Style 1.6.1 Consider the Django Coding Style Guidelines . 1.6.2 Use Underscores in URL Pattern N ames Rather lh an Dashes . 1.6.3 Use Underscores in TempIate BIock Names Rather FIhan D ashes 1.7 Choose JS, HTML, and CSS Style Guides . JavaScript Style Guides 1.7.1 1.7.2 HTML and CSS StyIe Guides 1.8 Never Code to the IDE ()r Text Editor) . Summary ・ 1.9 2 lhe OptimaI Django Environment Setup 2.1 Use the Same Database Engine Everywhere 2.1.1 You Can't Examine an Exact Copy of Production Data LocaIIy 2.1.2 Different Databases Have Different FieId Types/Constraints 2.1.3 Fixtures Are Not a Magic SoIution . 2.2 Use Pip and VirtuaIenv lnstall Django and Other Dependencies via Pip 2.4 Use a Version Contr01 System . 2.5 OptionaI: ldentical Environments . 2.5.1 Vagrant and VirtuaIBox . 2.6 Summary ・ 3 Howto Lay 0 題 t Django Projects 3.1 Django 1.8 ' s Default Project Layout . 3.2 Our Preferred Project Layout 3.2.1 Top LeveI: Repository Root . Second Leve1: Project Root 3.2.2 3.2.3 "lhird LeveI: Configuration Root SampIe Project Layout . 3.3 3.4 What About the VirtuaIenv? 3.5 G0ing Beyond startproject っ 0 っ 0 4- 戸 ) 一 5 一つ / 8 0 ノ 0 ′ . 0 1 -1 -1 1 1 1 1 1 1 1 っ ~ 1 1 亠フ 1 っ 0 っ 0 00 -4 一冖 / 8 VZtZ

Co 〃〃な 3.5.1 Generating Proj ect Boilerplate With C00 kiecutter . 3.5.2 Our Favorite Project Template 3.5.3 An Alternative Template: dj ango-kevi n 3.5.4 Other Alternatives S ummary . 3.6 4 FundamentaIs ofDjango App Design 4.1 %e Golden Rule of Django App Design . 4.1.1 A Practical Example ofApps in a Project . 4.2 What to Name Your Django Apps 4.3 When in Doubt, Keep Apps Small 4.4 What Modules Belong in an App? 4.4.1 Common App ModuIes . 4.4.2 Uncommon App Modules S ummary . 5 Settings and Requirements FiIes 5.1 Avoid Non-Versioned LocaI Settings 5.2 Using MuItip1e S etti ngs FiIes 5.2.1 A Deve10pment Settings Example 5.2.2 Multiple Development Settings . Separate Configuration From Code 5.3.1 A Caution Before Using Environment Variab1es for Secrets 5.3.2 How to Set Environment Variables Loc 心メ 5.3.3 How to Set Environment Variables in Production 5.3.4 Handling Missing Secret Key Exceptions 5.4 When You Can't Use Environment Variab1es 5.4.1 Using JSON Files . 5.4.2 Using Config, YAML, and XML File Formats 5.5 Using MuItipIe Requirements FiIes 5.5.1 I n stalling From MuItipIe Requirements FiIes . 5.5.2 Using Multip1e Requirements Files With Platforms as a Service (PaaS) . 5.6 HandIing FiIe Paths in Settings . 5.7 Summary . 9 0 1 っ 2 っ】っ 0 CO ( 0 4 戸 ) ・ 6 / 7 冖 / 8 0 っ 0 っ 0 っ 0 00 っ 0 一 4 4.5 ~ 1 つん 0 / 0 「 / 8 9. 9. ・ 1 っ ~ 4 4- 一、れ 6 / 4 4 4 4 。 4 、 4 4 4 一 5 1 ) 1 ) 1 ) 5 ) 1 ) 5 ) 5.3 「 / 8 -1 ZX

Co 〃〃倉 eo -4 ・ 4- -4- -6 【 / 0 ノノ 0 0 っっ 0 -4 冖 ) / 0 8 9. 0 ′ . 6 Mode1 Best Practices 6.1 B asiCS 6.1.1 Break Up Apps With T00 Many Models . 6.1.2 Be CarefuI 、 Vith ModeI lnheritance 6.1.3 ModeI lnheritance in Practice: FIhe TimeStampedModel 6.1.4 Database Migrations 6.2 Django M0del Design . S tart NormaIized 6.2.1 6.2.2 Cache Before Denormalizing . 6.2.3 DenormaIize OnIy ifAbs01utely Needed . 6.2.4 When to Use NuII and BIank . 6.2.5 When to Use BinaryFieId . 6.2.6 Try to Avoid Using Generic Relations 6.2.7 PostgreSQL-Specific FieIds: When to Use Nu11 and BIank 6.3 The Model -rneta API . 6.4 ModeI Managers . 6.5 Understanding Fat Models 6.5.1 Model Behaviors a. k. a Mixins State1ess Helper Functions 6.5.2 6.5.3 ModeI Behaviors vs Helper Functions 6.6 Summary ・ 7 Queries and the Database Layer 7.1 Use get-object-or-404() for Single Objects 7.2 Be CarefuI With Queries That Might FIhrow Exceptions . 7.2.1 ObjectDoesNotExist vs. DoesNotExist 7.2.2 When You Just Want One Object but Get lhree Back 7.3 Use Lazy Evaluation to Make Queries Legible 7.4 Lean on Advanced le T001S . 7.4.1 肥 Expressions 7.4.2 Database Functions 7.5 Don't Drop Down to Raw SQ!J UntiI lt's Necessary 7.6 Add lndexes as Needed 7.7 Transactions 7.7.1 Wrapping Each HTTP Request in a Transaction 7.7.2 Expli cit Transaction Declaration 1 1 亠つんっムっ 0 4 一 5 / 0 / 8 0 ノ′っ ~ 8 8 8 8 一 8 一 8 8 8 8 8 一 8 一 8 一 C ノ

CO 〃〃な 7.7.3 django. http.StreamingHttpResponse and Transactions Transactions in MySQJJ 7.7.4 7.7.5 Django ORM Transaction Resources . Summary . 3 4 4 4 9. 9. 9. 9. 8 Function- and Class-Based Views 8.1 When to Use FBVs or CBVs 8.2 Keep View Logic Out ofURLConfs Stick to Loose CoupIing in URLConfs . 8.3.1 What ifWe Aren't Using CBVs? 8.4 Use URL N amesp aces . Makes for Shorter, More Obvious and Don't Repeat Yourself URL 8.4.1 Names . lncreases lnteroperability With %ird-Party Libraries 8.4.2 Easier Searches, Upgrades, and Refactors 8.4.3 AIIows for More App and TempIate Reverse Tricks 8.4.4 Don't Reference Views as Strings in URLC onfs 8.5 8.6 Try to Keep Business Logic Out of Views 8.7 Dj ango Views Are Functions 8.7.1 lhe Simplest Views . Don't Use loca ls ( ) as Views Context . 8.8 Summary . 8.9 9 Best Practices for Function-Based Views 9.1 Advantages ofFBVs 9.2 Passing the HttpRequest Object 9.3 Decorators Are Sweet 9.3.1 Be Conservative With Decorators 9.3.2 AdditionaI Resources on Decorators 9.4 Passing the HttpResponse Object 9.5 Summary . 10 Best Practices for Class-Based Views 10.1 GuideIines When Working With CBVs 10.2 Using Mixins With CBVs . 10.3 Which Django GCBV Should Be Used for What Task? . - 、一 1 、】・ 6 8 -1 1 9. ′′ 0 -0 -1 1 . 102 . 103 . 104 . 104 . 104 . 105 . 106 . 107 . 107 . 109 111 . 111 . 112 . 115 . 117 . 118 . 118 . 118 119 . 120 . 120 . 122 Xt

10.4 Genera1 Tips for Django CBVs 10.4.1 Constraining Django CBV/GCBV Access to Authenticated Users 10.4.2 Performing Custom Actions on Views 、 Vith Valid Forms . 10.4.3 Performing Custom Actions on Views With lnvalid Forms 10.4.4 Using the View Object 10.5 How GCBVs and Forms Fit Together 10.5.1 Views + ModeIForm ExampIe 10.5.2 Views + Form ExampIe 10.6 Using Just django ・ views ・ generic. View . 10.7 AdditionaI Resources 10.8 Summary . 11 Form Fundamenta1s 11.1 11.2 11.3 11.4 11.5 11.6 Va1idate AII lncoming Data With Django Forms . Use the POST Method in HTML Forms AIways Use CSRF Protection With HTI 、 P Forms Modify Data . 11.3.1 Posting Data via AJAX Understand How to Add Django Form lnstance Attributes Know How Form VaIidation Works . 11.5.1 Mode1Form Data ls Saved to the Form, lhen the ModeI lnstance Add Errors to Formswith Form. add-error() 11.6.1 Other UsefuI Form Methods 11.7 Fields Without Pre-Made Widgets . 11.8 Additional Resources 11.9 Summary . 12 Common Patterns for Forms 12.1 12.2 12.3 12.4 12.5 12.6 Pattern 1 : Simp1e ModelForm With Default Validators Pattern 2 : Custom Form FieId VaIidators in ModeIForms Pattern 3 : Overriding the CIean Stage ofValidation Pattern 4 : Hacking Form Fie1ds ( 2 CBVs, 2 Forms, 1 Model) Pattern 5 : Reusable Search Mixin View . Summary ・ 13 Templates: Best Practices 13.1 Keep TempIates MostIyin temptates/ XZZ . 123 . 124 . 124 . 125 . 126 . 128 . 129 . 133 . 135 . 137 . 138 139 . 139 . 142 . 143 . 143 . 144 . 145 . 147 . 148 . 149 . 149 . 150 . 150 151 . 152 . 153 . 158 . 161 . 165 . 167 169 . 169

13.2 Template Architecture Patterns 13.2.1 2 -Tier Template Architecture Example 13.2.2 3-Tier Template Architecture Example 13.2.3 Flat ls Better FIhan Nested 13.3 Limit Processing in TempIates 13.3.1 Gotcha 1 : Aggregation in Templates 13.3.2 Gotcha 2 : Fi1tering With Conditionals in Temp1ates 13.3.3 Gotcha 3 : Complex lmplied Queries in Templates . 13.3.4 Gotcha 4 : Hidden CPU Load in Templates 13.3.5 Gotcha 5 : Hidden REST API Calls in Templates . 13.4 Don't Bother Making Your Generated HTML Pretty 13.5 ExpIoring TempIate lnheritance . 13.6 block. super Gives the Power of ControI . 13.7 Useful %ings to Consider 13.7.1 13.7.2 13.7.3 13.7.4 13.7.5 13.7.6 Avoid Coupling Styles T00 TightIy to Python Code . C01 れ mon Conventions Location, Location, Location! Use Named Context Objects Use URI. , Names lnstead of Hardcoded Paths Debugging C omplex Templates 13.8 Error Page Temp1ates 13.9 Follow a Minima1ist Approach 13.10 Summary . 14 Temp1ate T 雀 and FiIters 14.1 Filters Are Functions 14.1.1 Filters Are Easy to Test 14.1.2 Filters and Code Reuse 14.1.3 When to Write Filters 14.2 Custom TempIate Tags 14.2.1 TempIate Tags Are Harder to Debug . 14.2.2 TempIate Tags Make Code Reuse Harder 14.2.3 FIhe Performance Cost ofTempIate Tags 14.2.4 When to Write Template Tags 14.3 Naming Your Template Tag Libraries . 14.4 Loading Your TempIate Tag ModuIes . CO 〃た〃な . 170 . 170 . 171 . 172 . 173 . 175 . 177 . 179 . 180 . 181 . 182 . 183 . 186 . 188 . 188 . 188 . 189 . 189 . 190 . 190 . 191 . 192 . 193 195 . 195 . 196 . 196 . 197 . 197 . 197 . 197 . 197 . 198 . 199 . 199 XZ 〃

Co 〃〃な 14.4.1 Watch Out for 'lhis Crazy Anti-Pattern 15.1 What's the SyntacticaI Difference? 15 Django Temp1ates andJinja2 14.5 Summary . 15.2 ShouId I Switch? . 15.2.3 Which One Wins? 15.2.2 Advantages ofJi 可 a2 15.2.1 Advantages of DTL . 工 ZV 16.6.3 Are Remote Procedure Calls Easy to lmplement? 16.6.2 How Much BoiIerpIate Do You Want to Write? 16.6.1 Django Rest Framework ls the Defacto Package 16.6 EvaIuating REST Frameworks 16.5.2 Step # 2 : RepIace API With 410 Error View 16.5.1 Step # 1 : Notify Users of Pending Shut Down 16.5 Shutting Down an Externa1 API 16.4 Service-Oriented Architecture 16.3.6 Version Your API 16.3.5 Test Your API . 16.3.4 Grouping API URLs 16.3.3 Try to Keep Business Logic Out ofAPI Views 16.3.2 Code for an App ShouId Remain in the App . 16.3.1 Code for a Project Shou1d Be Neat1y Organized 16.3 REST API Architecture . 16.2 lmplementing a SimpIe JSON API 16.1 Fundamenta1s ofBasic REST API Design 16 Bui1ding REST APIs 15.5 Summary . 15.4 Resources 15.3.5 %e Jinja2 Environment Object ShouId Be Considered Static . 15.3.4 Context Processors Aren't CaIIed by Ji 可 a2 Temp1ates 15.3.3 Using Django-Sty1e TempIate FiIters in Jinja2 TempIates 15.3.2 Using TempIate Tags in Jinja2 TempIates 15.3.1 CSRF andJi 可心 15.3 Considerations When Using Jinja2 、 Mith Django . 200 . 200 203 . 203 . 204 . 204 . 205 . 205 . 206 . 206 . 206 . 206 . 208 . 210 . 211 . 212 213 . 214 . 216 . 219 . 219 . 220 . 220 . 221 . 223 . 223 . 224 . 224 . 225 . 225 . 226 . 226 . 226 . 226

16.6.4 CBVs or FBVs? 16.7 Rate Limiting Your API . 16.7.1 Unfettered API Access is Dangerous . 16.7.2 REST Frameworks Must Come with Rate Limiting . 16.7.3 Rate Limit Can Be A Business Plan 16.8 Advertising Your REST API 16.8.1 Documentation 16.8.2 Provide C1ient SDKs 16.9 AdditionaI Reading 16.10 Summary . 17 Consuming REST APIs 17.1 Learn How to Debug the Client 17.2 Consider Using JavaScript-Powered Static Asset Preprocessors 17.3 Making Content lndexable by Search Engines 17.3.1 Read the Search Engine Documentation . 17.3.2 Hand-Craft the sitemap.xml 17.3.3 Use a Service to Make Your Site Crawlable 17.4 Real-Time Woes a. k. a. Latency . 17.4.1 S01ution: Mask the Latency With Animations . 17.4.2 Solution: Fake SuccessfuI Transactions . 17.4.3 Solution: GeographicaIIy Based Servers 17.4.4 Solution: Restrict Users GeographicalIy 17.5 Avoid the Anti-Patterns . 17.5.1 Building Single Page Apps When Multi-Page Apps Suffce . 17.5.2 Not Writing Tests . 17.5.3 Not Understanding JavaScript Memory Management . 17.5.4 Storing Data in the DOM When lt's Not jQuery 17.6 AJAX and the CSRF Token . 17.6.1 J メ and the CSRF Token . 17.6.2 Backbone. js and the CSRF Token 17.6.3 AnguIarJS and the CSRF Token 17.7 lmproving JavaScript Ski11s 17.7.1 Assessing Skill Levels 17.7.2 Learn More JavaScript! 17.8 Follow JavaScript Coding Standards . 227 . 227 . 227 . 228 . 229 . 229 . 229 . 229 . 230 . 230 231 . 232 . 233 . 233 . 233 . 234 . 235 . 235 . 235 . 236 . 236 . 236 . 236 . 237 . 237 . 237 . 237 . 238 . 238 . 240 . 240 . 241 . 241 . 241 . 241

Co 〃〃ム 17.9 Useful Resources . 17.10 Summary . 18 Tradeoffs of Rep1acing Core Components 18.1 FIhe Temptation to BuiId FrankenDjango . 18.2 Non-ReIationaI Databases vs. Relationa1 Databases 19 Working 、 Vith the DjangoAdmin 18.4 Summary . 18.3 What About RepIacing the Django TempIate Language? 18.2.4 How We Use Non-ReIationaI Databases With Django 18.2.3 lgnore the Hype and Do Your Own Research 18.2.2 Don't Use Non-ReIationaI Databases for Re1ationaI Tasks 18.2.1 Not AII Non-Relational Databases Are ACID Compliant . 19.1 19.2 19.3 19.4 19.5 19.6 19.7 19.8 19.9 lt's Not for End Users . Admin Customization VS. New Views Viewing String Representations of Objects . Adding Callables to ModelAdmin Classes Don't Use list-editable in Multiuser Environments Django's Admin Documentation Generator Securing the Django Admin and Django Admin Docs Using Custom S kins With the Dj ango Admin . 19.8.1 Evaluation Point: Documentation is Everything 19.8.2 Write Tests for Any Admin Extensions You Create Summary . 20 Dea1ing 、 Vith the User Model 20.1 Use Django's T001s for Finding the User Model 20.1.1 Use settings. AUTH-USER-MODEL for Foreign Keys to User 20.1.2 Don't Use for Foreign Keys to User 20.2 Migrating Pre-I. 5 User ModeIs to 1.5 + ' s Custom User Models 20.3 Custom User FieIds for Django 1.8 Projects 20.3.1 Option 1 : Subclass AbstractUser 20.3.2 Option 2 : Subc1ass AbstractBaseUser . 20.3.3 Option 3 : Linking Back From a ReIated Model XVZ . 242 . 242 四 3 . 244 . 245 . 245 . 246 . 246 . 247 . 247 . 247 249 . 250 . 250 . 250 . 254 . 255 . 256 . 257 . 257 . 258 . 258 . 259 261 . 261 . 262 . 262 . 263 . 263 . 264 . 265 . 265

20.4 Summary . 21 Django's Secret Sauce: Third-Party Package 21.1 21.2 21.3 21.4 21.5 21.6 21.7 Examples of1hird-Party Packages Know About the Python Package lndex Know About DjangoPackages.com TooIs for lnstalling and Managing Packages Package Requirements . Wiring Up Django Packages: %e Basics 21.7.1 Step 1 : Read the Documentation for the Package 21.7.2 Step 2 : Add Package and Version Number to Your Requirements 21.7.3 Step 3 : lnstall the Requirements lnto Your Virtualenv . 21.7.4 Step 4 : Follow the Package's lnstallation lnstructions Exactly 21.8 TroubIeshooting FIhird-Party Packages 21.9 Releasing Your Own Django Packages 21.10 What Makes a Good Django Package? 21.10.1 21.10.2 21.10.3 21.10.4 21.10.5 21.10.6 21.10.7 21.10.8 21.10.9 Purpose Scope Documentation Tests . Templates Activity Community ModuIarity Availability on PyPI . 21.10.10 Uses the Broadest Requirements Specifiers Possible 21.10.11 Proper Version Numbers 21.10.12 Name 21.10.13 License 21.10.14 CIarity of Code 21.10.15 Use URL Namespaces 21.11 Creating Your Own Packages the Easy Way 21.12 Maintaining Your Open Source Package 21.12.1 Give Credit for PuII Requests . 21.12.2 HandIing Bad PuII Requests CO 〃た〃な . 267 269 X 〃 . 283 . 283 . 283 . 282 . 281 . 281 . 281 . 280 . 279 . 278 . 277 . 277 . 277 . 277 . 276 . 276 . 276 . 276 . 275 . 275 . 274 . 274 . 274 . 273 . 272 . 272 . 272 . 272 . 271 . 271 . 271 . 270 . 270

CO 〃〃な 21.12.3 21.12.4 21.12.5 21.12.6 21.12.7 21.12.8 Do FormaI PyPI Re1eases . Create and Deploy Wheels to PyPI Upgrade the Package to New Versions 0fDjango FoIIow Good Security Practices . Provide S ample B ase Temp1ates Give the Package Away . 21.13 AdditionaI Reading 21.14 Summary . 22 Testing Stinks and ls 、 vaste ofMoney! 22.1 22.2 22.3 22.4 22.5 22.6 22.7 22.8 Testing Saves Money, Jobs, and Lives . How to Structure Tests How to Write Unit Tests 22.3.1 22.3.2 22.3.3 22.3.4 22.3.5 22.3.6 22.3.7 22.3.8 22.3.9 22.3.10 Each Test Method Tests One "lhing For Views, When PossibIe Use the Request Factory Don't Write Tests lhat Have to Be Tested Don't Repeat YourseIfDoesn't AppIy to Writing Tests Don't Rely on Fixtures "lhings lhat Should Be Tested Test for Failure Use Mock to Keep Unit Tests From Touching the WorId Use Fancier Assertion Methods . D ocument the Purpo se of Each Test What About lntegration Tests? Continuous lntegration Who Cares? We Don't Have Time for Tests! lhe Game ofTest Coverage . Setting Up the Test Coverage Game 22.8.1 Step 1 : Start Writing Tests 22.8.2 Step 2 : Run Tests and Generate Coverage Report 22.8.3 Step 3 : Generate the Report! 22.9 Playing the Game ofTest Coverage . 22.10 Alternatives to unittest 22.11 Summary . 23 D ocumentation : Be Obsessed XVZZZ . 284 . 285 . 286 . 286 . 287 . 287 . 288 . 288 289 . 289 . 290 . 291 . 291 . 294 . 295 . 295 . 296 . 296 . 298 . 298 . 300 . 301 . 301 . 302 . 302 . 303 . 303 . 304 . 304 . 305 . 305 . 306 . 307 309

23.1 23.2 23.3 23.4 23.5 Use reStructuredText for Python Docs Use Sphinx to Generate Documentation From reStructuredText . What Docs ShouId Django Projects Contain? Additional l)ocumentation Resources . lhe Markdown Alternative 23.5.1 README. md to README. rst: Using Pandoc for Packages Up- 23.5.2 Markdown Resources . loaded to PyPI 23.6 Wikis and Other Documentation Methods . 23.7 Summary . 四 Finding and Reducing BottIenecks 24.1 Should You Even Care? 24.2 Speed Up Query-Heavy Pages 24.2.1 Find Excessive Queries With Django Debug Toolbar 24.2.2 Reduce the Number of Queries . 24.2.3 Speed Up Common Queries 24.2.4 Switch ATOMIC REQUESTS to False . 24.3 Get the Most Out ofYour Database 24.3.1 Know What Doesn't Belong in the Database . 24.3.2 Getting the Most Out of PostgreSQJJ 24.3.3 Getting the Most Out ofMySQJ. , 24.4 24.5 24.6 24.7 24.8 24.9 24.10 Cache Qyeries With Memcached or Redis ldentify Specific PIaces to Cache Consider FIhird-Party Caching Packages Compression and Minification of HTML, CSS, and JavaScript Use Upstream Caching or a Content DeIivery Network Other Resources . Summary . 25 Asynchronous Task Queues 25.1 Do We Need a Task 肥 u 25.2 Choosing Task Queue Software . 25.3 Best Practices for Task Queues 25.3.1 Treat Tasks Like Views . 25.3.2 Tasks Aren't Free CO 〃〃な . 309 . 311 . 312 . 313 . 313 XZX . 330 . 330 . 330 . 329 . 328 327 . 326 . 324 . 324 . 323 . 322 . 322 . 322 . 321 . 321 . 320 . 320 . 320 . 319 . 318 . 317 . 317 . 317 317 . 315 . 315 . 314 . 314

Co 〃〃倉 25.3.3 25.3.4 25.3.5 25.3.6 25.3.7 25.3.8 25.3.9 25.3.10 On1y Pass JSON-SeriaIizabIe Va1ues to Task Functions Learn How to Monitor Tasks and 、 vorkers Logging! ・ Monitor the Backlog Periodica11y Clear Out Dead Tasks lgnore Results We Don't Need Use the Queue's Error Handling Learn the Features ofYour Task Queue Software 25.4 Resources for Task Queues 25.5 Summary . 26 Security Best Practices 26.1 Harden Your Servers . 26.2 Know Django's Security Features 26.3 Turn Off DEBUG Mode in Production 26.4 Keep Your Secret Keys Secret 26.5 HTTPS Everywhere 26.5.1 Use Secure Cookies 26.6 Use AIIowed Hosts VaIidation . 26.5.3 HITPS Configuration T001S . 26.5.2 Use HTTP Strict Transport Security (HSTS) 26.12.1 When a CDN ls Not an Option 26.12 HandIe User-Up10aded FiIes CarefuIIy 26.11 DisabIe the AutocompIete on Payment Fie1ds 26.10 VaIidate AII lncoming Data With Django Forms . 26.9.4 Be CarefuI With Cookie-Based Sessions . 26.9.3 T1ird-Party Libraries lhat Can Execute Code 26.9.2 Python Standard Library ModuIes %at Can Execute Code 26.9.1 Python BuiIt-Ins FIhat Execute Code 26.9 Defend Against Python Code I 可 ection Attacks 26.8.4 AdditionaI Reading 26.8.3 Use JSON Encoding for Data Consumed byJavaScript 26.8.2 Don't A110W Users to Set lndividual HTML Tag Attributes . 26.8.1 Use Django Temp1ates Over mark-safe . 26.8 Prevent Against Cross-Site Scripting (XSS) Attacks 26.7 AIways Use CSRF Protection With HTTP Forms 'lhat Modify Data . . 331 . 331 . 331 . 332 . 332 . 332 . 332 . 333 . 333 . 334 335 . 335 . 335 . 336 . 336 . 336 . 338 . 338 . 340 . 340 . 341 . 341 . 341 . 341 . 342 . 342 . 342 . 342 . 343 . 343 . 343 . 345 . 345 . 345 . 346

26.12.2 Django and User-UpIoaded FiIes . 26.13 Don't Use ModelForms. Meta. exclude . 26.13.1 Mass Assignment VulnerabiIities 26.14 Don't Use ModelForms . Meta . fietds 26.15 Beware of SQJ. , I 可 ection Attacks 26.16 Never Store Credit Card Data . 26.17 Secure the Django Admin . 26.17.1 Change the DefauIt Admin URL 26.17.2 Use django-admin-honeypot —all— 26.17.3 Only Allow Admin Access via HTTPS 26.17.4 Limit Admin Access Based on IP 26.17.5 Use the allow-tags Attribute With Caution Secure the Admin Docs Monitor Your Sites Keep Your Dependencies Up-to-Date Prevent CIickjacking . Guard Against XML Bombing With defusedxml Exp10re Two-Factor Authentication Embrace SecurityMiddIeware . 26.25 Force the Use of Strong Passwords Give Your Site a S ecurity C heckup Put Up a VuInerabiIity Reporting Page Stop Using django. utils. html. remove-tag Have a PIan Ready for When %ings Go Wrong . 26.29 26.28 26.27 26.26 26.24 26.23 26.22 26.21 26.20 26.19 26.18 27.1 AppIication Logs vs. Other Logs 27 Logging: 、 Vhat's lt For, Anyway? 26.33 Summary . 26.32 Keep Up-to-Date on GeneraI Security Practices 26.31 Reference Our Security Settings Appendix 26.30 Obfuscate Primary Keys with UUIDs . 26.29.5 Start Looking lnto the ProbIem 26.29.4 Emai1 security@djangoproject.com/ Even iflt's Your Fault 26.29.3 Back Everything Up 26.29.2 Put Up a Static HTML Page 26.29.1 Shut Everything Down or Put lt in Read-OnIy Mode . CO 〃た〃な . 346 . 347 . 350 . 350 . 350 . 351 . 351 . 351 . 352 . 352 . 353 . 353 XXt . 363 363 . 362 . 362 . 361 . 360 . 359 . 359 . 358 . 358 . 358 . 357 . 357 . 357 . 356 . 356 . 356 . 355 . 354 . 354 . 354 . 353 . 353

27.2 Why Bother With Logging? 27.3 When to Use Each Log Leve1 . 27.3.1 Log Catastrophes 、 Vith CRITICAL 27.3.2 Log Production Errors With ERROR 27.3.3 Log Lower-Priority ProbIems With WARNING 27.3.5 Log Debug-Re1ated Messages to DEBUG . 27.3.4 Log UsefuI State lnformation With INFO . 27.4 27.5 27.6 27.7 27.8 27.9 27.10 Log Tracebacks When Catching Exceptions One Logger Per Module %at Uses Logging Log Locally to Rotating Files Other Logging Tips Necessary Reading Material UsefuI FIhird- Party TooIs Summary . 28 Signals: Use Cases and Avoidance Techniques 28.1 When to Use and Avoid SignaIs 28.2 Signa1 Avoidance Techniques 29.3 Django's Own Swiss Army Knife 29.2.3 Easier Testing 29.2.2 Trimming ModeIs . 29.2.1 Storing Code Used in Many PIaces . 29.2 Optimize Apps with UtiIity Modules 29.1 Create a Core App for Your UtiIities 29 、 Vhat About Those Random Uti1ities? 28.3 Summary . 28.2.4 Use a HeIper Function lnstead of Signa1s . 28.2.3 Override Your ModeI's Save or DeIete Method lnstead 28.2.2 VaIidate Your ModeI EIsewhere . 28.2.1 Using Custom ModeI Manager Methods lnstead of SignaIs 29.3.1 29.3.2 29.3.3 29.3.4 29.3.5 X 〃 dj ango. contrib. humanize 可 ango. utils. decorators. method-decorator(decorator) . 可 ango ・ utils. decorators. decoratorfrom—middleware (middleware) django ・ utils. encoding. force-text(value) django. utils. functional.cached-property . 364 . 364 . 365 . 365 . 366 . 367 . 367 . 369 . 370 . 370 . 371 . 372 . 372 . 372 373 . 373 . 374 . 374 . 377 . 377 . 378 . 378 379 . 379 . 380 . 380 . 380 . 381 . 381 . 382 . 382 . 383 . 383 . 383

29.3.6 29.3.7 29.3.8 29.3.9 29.3.10 29.3.11 29.3.12 dj ango. utils. html. formathml(format-str, *args , **kwargs) django. utils. html. remove-tags(value, tags) django. utils. html. strip-tags(value) . 可 ango ・ utils. six . django. utils. text. slugify(value) . django. utils. timezone django. utils. translation 29.4 Exceptions . 29.4.1 django. core. exceptions. ImproperlyConfigured 29.4.2 django ・ core. exceptions. ObjectDoesNotExist 29.4.3 django. core. exceptions. PermissionDenied 29.5 S erializers and D eserializers . 30.1 Evaluating a PaaS 30 Dep10yment: P1atforms as a Service 29.6 Summary . 29.5.3 django. core. serializers. xml-serializer 29.5.2 django ・ core. serializers. pyyaml 29.5.1 django ・ core. serializers. json. DjangoJSONEncoder 30.1.1 30.1.2 30.1.3 30.1.4 30.1.5 30.1.6 30.1.7 30.1.8 30.1.9 Compliance Pricing . Uptime S taffng Sca1ing . Documentation Performance Degradation . Geography ・ Company Stability 30.2 Best Practices for Deploying to PaaS 30.2.1 Aim for ldentical Environments 30.2.2 Automate AII the lhings! 30.2.3 Maintain a Staging lnstance 30.2.4 Prepare for Disaster With Backups and Rollbacks 30.2.5 Keep ExternaI Backups 30.3 Summary . . 384 . 384 . 384 . 385 . 385 . 387 . 387 . 387 . 387 . 387 . 389 . 390 . 392 . 393 . 393 . 393 395 . 396 . 396 . 397 . 397 . 398 . 399 . 399 . 399 . 400 . 400 . 401 . 401 . 401 . 402 . 402 . 402 . 402 XXttZ

Co 〃〃な 31 Deploying Django Projects 31.1 31.2 31.3 31.4 31.5 31.6 Single-Server for Sma11 Projects . 31.1.1 ShouId You Bother? . 31.1.2 Examp1e: Quick Ubuntu + Gunicorn Setup Multi-Server for Medium to Large Projects 31.2.1 Advanced MuIti-Server Setup WSGI App1ication Servers Performance and Tuning: uWS GI and Gunicorn . StabiIity and Ease of Setup: Gunicorn and Apache . Common Apache Gotchas 31.6.1 Apache and Environment Variables . 31.6.2 Apache and VirtuaIenv 31.7 Automated, Repeatable Deployments . 31.7.1 A RapidIy Changing WorId . 31.8 Which Automation T001 ShouId Be Used? 31.8.1 T00 Much Corporate FIuff 31.8.2 Do Your Own Research . 31.9 Current lnfrastructure Automation T001S 31.10 Other Resources . 31.11 Summary . 32 Continuous lntegration 32.1 PrincipIes of Continuous I ntegration 32.1.1 Write Lots ofTests! 32.1.2 Keeping the BuiId Fast 32.2 T001S for Continuous1y lntegrating Your Project 32.2.1 Tox 32.2.2 Jenkins . 32.3 Continuous lntegration as a Service . 32.3.1 Code Coverage as a Service . 32.4 Additional Resources 32.5 Summary . 33 The Art ofDebugging 33.1 Debugging in Deve10pment . 33.1.1 Use django-debug-toolbar XXZV 5 . 405 . 405 . 406 . 407 . 410 . 411 . 412 . 413 . 413 . 413 . 414 . 414 . 416 . 417 . 418 . 418 . 418 . 421 . 421 423 . 424 . 424 . 424 . 425 . 425 . 426 . 426 . 427 . 427 . 427 429 . 429 . 429

33.1.2 33.1.3 33.1.4 33.1.5 "lhat Annoying CBV Error Master the Python Debugger . Remember the Essentials for Form File UpIoads Lean on the Text Editor or IDE 33.2 Debugging Production Systems . 33.2.1 Read the Logs the Easy Way 33.2.2 Mirroring Production . 33.2.3 UserBasedExceptionMiddIeware 33.2.4 lhat Troublesome setti ngs. ALLOWED_HOSTS Error . 33.3 Feature F1ags . 33.3.1 Feature Flag Packages . 33.3.2 Unit Testing Code Affected by Feature F1ags 33.4 Summary . 34 、 Vhere and How to Ask Django Questions 34.1 34.2 34.3 34.4 34.5 What to Do When You're Stuck How to Ask Great Django Questions in IRC Feed Your Brain lnsider Tip: Be Active in the Community 34.4.1 9 Easy Ways to Participate Summary . 35 CIosing qhoughts Appendix A: Packages Mentioned ln This Book Appendix B: Troubleshooting lnstallation ldentifying the lssue . Our Recommended Solutions . Check Your Virtualenv lnstallation . Check IfYour VirtuaIenv Has Django 1.8 lnstalled Check For Other Problems . Appendix C: AdditionaI Resources Two Scoops Academy . Intermediate/Advanced Django MateriaI . Beginner Django Material . 429 . 431 . 431 . 434 . 434 . 435 . 435 . 435 . 436 . 437 . 438 . 438 . 438 439 . 439 . 439 . 440 . 441 . 441 . 442 3 5 453 . 453 . 454 . 454 . 455 . 455 457 . 457 . 458 . 460 XXV

Beginner Python Materia1 Useful Python Material JavaScript Resources Appendix D: lnternationalization and Localization Start EarIy . 、 vrap Content Strings with Translation Functions . Don't lnterpolate 、 vords in Sentences Browser Page Layout Appendix E: S ettings Alternatives Twe1ve Factor-Style Settings Appendix F: 、 vorking with Python 3 Most CriticaI Packages Work with Python 3 . Use Python 3.3.3 or Later . Working With Python 2 and 3 R. e sources Appendix G: Security Settings Reference Cross Site Request Forgery Protection Settings Email SSL . SESSION-SERIALIZER Acknowledgments List ofFigures List ofTab1es I ndex XXVZ . 461 . 461 . 462 463 . 463 . 464 . 465 . 468 471 . 471 473 . 473 . 475 . 475 . 476 477 . 478 . 478 . 478 479 484 487 489

List ofFigures 1 Tirowing caution tO the wind. 1.1 USing mpo rt ☆ in an ice Sh()P. 2.1 Pip, virtualenv, and virtualenvwrapper in ice cream b ar form. 3.1 Yet another reason why repositories are important. 3.2 %ree-tiered scoop layout ・ 3.3 An iSOlated environment, allO 、 your ice cream tO s 、 freely. 3.4 project layout differences ofopinion can cause ice cream fights. 4.1 lt'll make more sense when you turn the page ・ 4.2 Did that make sense? If not, read it agam ・ 4.3 Our vision for lcecreamlandia. 4.4 Two small, single-flavor pints are better than a giant' l()()-flavor container. 5.1 As your project grows, your l)jango settings can get pretty complex. 5.2 WhiIe we're at it, let's go down this path. 6.1 cones migrating south for the winter. Dj ango's built-in migration system started out as an external project called South. 6.2 A. C0n11 source Of confusion. 7.1 flavor Ofice cream contains raw SQJ-J a bit chewy. 7.2 Because no one loves ice cream a database. 8.1 Should you use a FBV or a CBV? flow chart. 8.2 Loose coupfing of chocolate chip cookie dough ice cream. 9.1 lfyou 100k at sprinkles closely, you'll see that they're PYthon decorators. 8 17 00 4 7 っ ~ っ ~ っ ~ っ っ 0 一 4 一 -6 行 / 00 00 っ 0 41 59 68 72 88 93 96 98 . 117 イ 84

Popular and unpopular mmns used in ice cream. 10.2 lhe other CBV: class-based vanilla ice cream. 10.3 Views + Mode1Form FIow 10.4 Views + Form F10w 、 Vhen ice cream validation 儀 ils. At Tasty Research, every flavor must begin with "Tasty" Why would they do this to us? An excerpt 伝 om the Zen oflce Cream. Two Scoops, 0 伍 cial halftime sponsor ofthe super BowI. 21.2 21.1 20.1 19.6 19.5 19.4 19.3 19.2 19.1 18.1 17.1 16.1 14.1 13.3 13.2 13.1 12.2 12.1 11.1 10.1 lhe secret is out. lt's just hot fudge. A jar Of Django s mysterious secret sauce. Most don't have a clue what this is. lhis 100kS strange t00. Displaying URL in the Django Admin. Further improvements to the admin list page. 、 Vhat? An admin interface for ice cream bars? lmproved admin list page with better string representation ofour objects. Admin list page for an ice cream bar 叩 p. Chocolate chip ice cream with an admin interface. Which cake would win? FIhe one on the right, of course. Replacing more core components ofcake with ice cream seems like a good idea. Server—side VS. client—side ice cream. 16.2 An lce Cream as a Service API. A tasty pie is one filled with ice cream. Flhis filter transforms 1 ー 2 flavors of ice cream into vanilla, outputting to a cone. BubbIe gum ice cream 100kS easy to eat but reqmres a 10t ofprocessing. 23.1 Even ice cream could benefit 伝 om documentation. 22.1 Test as much ofyour project as メ ou can, as if it were free ice cream. . 196 . 120 . 126 . 129 . 133 . 146 . 153 . 161 . 172 . 174 . 181 . 214 . 221 . 232 . 245 . 249 . 250 . 252 . 252 . 253 . 255 . 262 . 269 . 270 . 297 . 313 485

んⅳ F 肝 lnfrastructure automation can be very po 、 How ice cream is deployed to cones and bowls. Example of an advanced multi-server setup. Manag1ng an ice cream replenishment process with Supervisord. Example of a basic multi-server setup ・ 29.2 Six smooths over the differences between 2 and 3. . A. utility belt for serious ice cream eaters. Appropriate usage of DEBUG logging in ice cream ・ CRITICAL/ERROR/WARNING/INFO logging in ice cream. With your site runmng smoothly, you'll be feeling as C001 as a cone ・ 24.1 27.1 27.2 29.1 31.1 31.2 31.3 31.4 31.5 31.6 32.1 34.1 486 . 325 . 364 . 369 . 382 . 385 . 408 . 409 . 410 . 414 . 416 Hopefu11y, one day someone will invent a one-button machine that deploys Django projects and makes ice cream. lt's easy tO get carried away. Pictured are tWO absolutely unnecessary TOX envl- . 421 ronments, just SO we could get extra tastes. 1he ice cream eating help desk. . 426 . 442

List ofTab1es Author's lce Cream Preferences . 1.1 lmports: AbsoIute vs. ExpIicit ReIative vs. lmplicit Relative 3.1 Repository Root Files and Directories 3.2 Django Project Files and Directories 5.1 Settings files and their purpose 5.2 Setting DJANGO-SETTINGSMODULE per location . 6.1 Pros and Cons of the ModeI lnheritance Styles 6.2 When to Use Null and Blank by Field 6.3 When to Use NuII and Blank for Postgres Fields . 7.1 When to Use Transactions Django CBV Usage TabIe . 10.1 Template Tags in base. html 13.1 TempIate O bj ects in about. html 13.2 DTL vs Ji 可 a2 Syntax Differences 15.1 DTL vs Ji 可心 Syntax Similarities 15.2 16.1 HTTP Methods 16.2 HTTP Status Codes 16.3 URLConf for the Flavor REST APIs Fad-based Reasons to Replace Components of Django 18.1 Documentation Django Projects Should Contain 23.1 XXXIII 7 25 26 44 45 93 . 122 . 184 . 186 . 203 . 204 . 214 . 216 . 218 . 244 . 312 487

力なーグ 7 みな 25.1 25.2 31.1 31.2 31.3 32.1 35.1 35.2 488 ShouId a Project Have a Task Queue? Comparing Task Queue S0ftware Gunicorn vs Apache vs uWSGl TimeIine of DevOps T001S lnfrastructure Automation T001 Comparison . Continuous lntegration Services dj ango. utils. translatio n Function Reference . S ecurity S ettings Reference . . 328 . 329 . 412 . 417 . 420 . 427 . 464 . 477

lndex —settings, 44 , 45 く configuration—root>, 23 <django-project-root>, 23 , 26 <repository•oot>, 23 , 25 , 26 , 56 Acknow1edgments, 479 ー 483 ACID, 89 , 245 ー 247 AbstractUser, 264 AbstractBaseUser, 265 abstract base classes, 64 ー 67 , 80 { { block. super } } , 18 188 { % static % } , 184 { % load % } , 184 { % include % } , 189 { % extends % } , 186 { % block%}, 184 , 186 , 189 —unicode--(), 253 , 476 —str—(), 251 ー 253 , 476 App Englight, 372 , 448 Environment VariabIes, 49 , 413 Apache, 49 , 323 , 324 , 408 , 411 ー 414 Ansib1e, 414 Angu1arJ s, 240 ALLOWEDNIOSTS, 336 , 436 ー 437 allow-tags warning, 255 , 353 AJAX, 143 ー 144 , 213 , 216 , 235 , 238 ー 240 Two Scoops Academy, 457758 , 460 Additional Resources, 457 ー 462 assertions, 30g301 assets/, 27 Asynchronous Task Queues, 327 ー 334 ATOMICREQUESTS, 320 489 CSRF, 143 ー 144 , 238 ー 240 , 335 , 341 , 366 CouchDB, 244 475 Continuous lntegration, 91 , 302 , 423 ー 427 , 408 Content Delivery Networks, 324 , 345 ー 346 , Coding StyIe, 1 ー 12 clean() methods, 146 , 158 ー 160 138 , 189 , 213 , 227 , 318 Class-Based Views, 95 ー 109 , 114 ー 115 , 118 ー Chef, 414 ー 420 CDN, 化ど Content Delivery Networks CBVs, C1ass-Based Views C as sandra, 244 326 , 374 , 447 caching, 69 , 173 , 198 , 243 , 318 , 319 , 322 ー 323 , Brunch, 11 Bottleneck AnaIysis, 91 , 317 ー 326 BitBucket, 18 , 271 , 275 , 426 BASEDIR, 58 イ 0 Backbone. js, 240 Avoid Using lmport * , 7 ー 8 , 47

ル x CSScomb, 11 custom field validators, 153 , 154 , 156 , 158 Custom User models, 261 ー 267 mirroring production, debugging, 429 ー 438 DEBUG, 44 , 46 , 47 , 336 database normafizatio n, 69 ー 70 Database Migrations, 68 database, 81 435 django-admin. py startproject, 21 ー 24 django-admin. py, 18 , 21 ー 24 , 28 ー 31 , 45 , 53 Secure the Django Admin, 351 ー 353 Django's Admin, 249 ー 259 Django Templates and Ji 可 a2, 203 ー 212 Django Packages, 269 ー 288 , 303 Django Coding Style Guidelines, 9 ー 10 deployment, 395 ー 403 , 405721 , 446 ー 447 denormalization , 69 ー 70 , 244 , 247 Decorators, 115 ー 118 436 UserB asedExceptionMiddIeware, 435 ー django. db. models, 63 ー 77 django. db. transaction, 89 ー 94 django. http.HttpResponse, 125 django. http.HttpResponseForbidden, 389 django. http.HttpResponseRedirect, 125 django. http.StreamingHttpResponse, 93 ー 94 dj ango. utils. decorators decoratorffrom-rniddleware, 382 ー 383 method-decorator, 382 django. utils. encoding. force-text, 383 , 468 django. utils. functional.cached-property, 383 django. utils. html. remove-tags(), 384 django. utils. html. strip-tags(), 384 django. utils. html. timezone, 387 django. utils. six, 385 django. utils. translation, 387 , 464 ー 466 django. views. generic. View, 119 , 122 ー 123 , 135 ー 137 DJANGOSETTINGSNIODULE, 45 Documentation, 256 ー 257 , 309 ー 315 docutils, 257 Don't Repeat Yourself, 41 , 43 , 98 , 100 , 102 , django ・ contrib. admin, 249 ー 259 , 331 , 351 ー 353 163 , 200 , 295 django. contrib. admindocs, 256 ー 259 , 353 django. contrib. humanize, 382 django ・ contrib. messages, 13 ( ト 133 django. core. exceptions ImproperlyConfigured, 387 ObjectDoesNotExist, 387 ー 388 PermissionDenied, 112 , 389 dj ango. core. serializers json. DjangoJSONEncoder, 392 pyyaml, 393 xml-serializer, 393 django. db, 63 ー 80 django. db. migrations, 67 イ 8 490 environment variables, 48 ー 55 Environment VariabIes Pattern, 48 ー 54 , 471 Error Page Templates, 191 ー 192 eval() , 342 exec() , 342 execfile(), 342 ExpIicit ReIative lmports, 4 ー 7 Fat Models, 77 ー 79 FBVs, 砒 Function-Based Views Feature FIags, 437 ー 438 FileField, 72

filters, 195 ー 197 , 297 fixtures, 15 , 296 form. is-valid(), 146 form-invalid, 148 formänvalid(), 125 ー 126 form-valid(), 124 ー 125 , 131 ー 133 , 146 , 353 Forms, 8 , 124 ー 135 , 139 ー 168 , 345 , 347 ー 350 Generic Class-Based Views, 119 , 122 ー 123 , GCBVs, Generic Class-Based Views functools. wraps(), 117 135 ー 137 , 213 Function-Based Views, 90 , 95 ー 109 , 111 ー 118 , FrankenDjango, 243 get-0bject-or-404(), 81 , 388 get-env-setting(), 52 , 53 getAolute-ur1(), 254 136 ー 138 , 450 ー 451 lmproperlyConfigured, 53 i18n, 463 ー 469 HttpResponse, 115 ー 118 HttpRequest, 112 ー 117 Heroku, 51 , 358 , 395 ー 403 , gulp.js, 233 Gulp, 11 Grunt, 11 GitHub, 18 , 271 , 273 , 275 , 357 , 426 Git, 18 , 22 , 273 , 275 , 423 get-secret(), 53 ー 55 447 is-valid(), 146 lntegration Tests, 301 ー intcomma, 382 INSTALLED-APPS, 33 , 256 indexes, 80 , 88 ー 89 302 JavaScript, 231 ー 242 Jenkins, 426 Ji 可心, 203 ー 212 context processors, 208 ー 210 CSRF, 206 Django-sty1e Filters, 206 ー 208 ji 可心 . Environment, 21 ( ト 211 Template Tags, 206 JQuery, 238 ー 240 JSCS, 11 JSON, 54 ー 55 , 136 , 213 , 216 ー 219 , 223 , 230 , 292 , 296 , 33g331 , 336 , 341 , 343 ー 344 , 389 ー 392 , 413 Keep lt Simple, Stupid, xxxiii kept out ofversion control, 42 KISS, xxxiii license, ⅱ Linux, 14 , 19 , 27 , 28 , 49 , 371 , 454 local-settings anti-pattern, 42 ー 43 , 48 , 54 , 471 logging, 363 ー 372 CRITICAL, 364 , 365 DEBUG, 364 , 367 ー 369 ERROR, 364 , 365 exceptions, 369 ー 370 INFO, 364 , 367 WARNING, 364 , 366 loggly.com/ 372 logrotate, 371 L 00 se coupling, 97 ー 98 , 100 Mac OSX, 14 , 19 , 27 , 28 , 49 , 315 , 371 , 454 makemigrations, 68 manage. py, 18 , 53 marksafe, 341 Markdown, 313 ー 315 イ 97

Memcached, 245 , 319 , 321 , 322 , 408 , 447 Mercurial, 18 , 25 , 275 , 423 Meta. exclude, 347 ー 350 Meta. fields, 347 ー 350 method resolution order, 121 mixins, 120 ー 121 , 132 , 133 , 167 , 380 Migrations, 67 ー 68 MIGRATIONMODULES, 68 Never Code to the IDE, 11 ー 12 NASA, xxvii, 289 MySQJ. ,, 14 , 68 , 94 , 178 , 32 ( ト 322 , 408 MuItipIe Settings Files, 4378 multi-table inheritance, 64 , 65 , 67 Mozi11a, 468 ー 469 MongoDB, 244 models. 石 eld. GenericForeign Key, 73 ー warning, 72 ー 73 models. field. B inaryField, 72 ー 73 models, 8 , 63 ー 80 162 , 347 ー 349 , 377 Mode1Forms, 146 , 147 , 151 , 152 , 156 , 158 , model managers, 76 ー 77 , 374 , 375 model -meta, 75 mod-wsgi, 408 74 350 , 468 180 , 244 , 267 , 277 , 296 , 318 , 319 , ORM, xxxiv, 14 , 63 ー 94 , 133 , 146 , 176 , 178 , Open Source Licenses, 281 Open Source lnitiative, 281 NoSQJ. ,, 244 ー 247 node. js, xxvii, 233 Nginx, 54 , 323 , 324 , 411 ー 414 Newrelic, 448 492 PaaS, Platforms as a Service Packages A-D awesome-slugify, 386 , 451 bleach, 357 , 449 cached-property, 383 ー 384 celery, 181 , 329 ー 330 , 333 , 373 , 409 , 446 circus , 446 cookiecutter, 281 ー 282 , 287 , 448 C00 kiecutter-dj ango, 28 ー 31 coverage. py, 290 , 303 ー 306 , 449 CSScomb, 11 , 447 defusedxml, 347 , 35 355 , 393 , 449 django-htmlmin, 324 , 451 django-heroku-memcacheify, 447 django-haystack, 451 django-forms-builder, 447 django-forms-bootstrap, 151 , 447 django-floppyforms, 151 , 447 , 473 django-extra-views, 138 , 451 django-extensions, 63 , 80 , 318 , 451 320 , 429 , 445 , 473 django-debug-toolbar, 44 , 104 , 288 , 317 ー django-db-tools, 358 , 446 473 django-crispy-forms, 151 , 198 , 279 , 447 , django-compressor, 324 , 451 473 135 ー 137 , 152 , 156 , 213 , 318 , 450 , django-braces, 119 , 12 127 , 13 132 , django-background-tasks, 329 ー 331 , 333 django-axes, 449 django-autoadmin, 356 , 449 django-allauth, 450 django-admin-honeypot, 352 , 449 dj-stripe, 451 dj-database-url, 447

django-jsonview, 213 , 448 django-model-utils, 63 , 80 , 445 django-passwords, 356 , 449 django-pipeline, 324 , 451 django-ratelimit-backend, 449 django-rest-framework, 143 , 213 , 215 ー 219 , 227 , 448 , 473 django-reversion, 451 django-rq, 446 django-secure, 356 , 449 django-tastypie, 143 , 213 , 215 , 219 , 448 django-two-factor-auth, 449 django—user—sessions, 449 django-vanilla-views, 138 , 451 django-watson, 451 django-wysiwyg, 198 flower, 446 Packages E-O envdir, 452 fabric, 25 , 420 , 447 儀 cto boy, 296 , 450 flake8, 2 , 452 gunicorn, 408 , 411 ー 414 pathlib, 452 invoke, 447 celery, 331 Packages P-Z model mommy, 296 , 450 mock, 296 , 450 Mock, 298 ー 300 logutils, 371 , 448 JSCS, 11 , 447 ji 可心, 203 ー 212 , 244 ipdb, 431 , 445 invoke, 25 , 420 , 447 ル x paver, 25 peep, 449 pillow, 445 , 473 pip, 15 , 17 , 20 , 256 , 257 , 270 ー 271 , 275 , 280 , 287 , 288 , 309 , 445 , 455 pip-tools, 452 psycopg2, 446 pytest, 450 pytest-django, 450 python-dateutils, 451 python-requests, 473 python-social-auth, 450 pytz, 451 pyYAML, 343 , 392 ー 393 pyyaml, 452 Redis Queue, 329 ー 331 , 333 requests, 452 rq, 409 , 446 silk, 318 , 452 sphinx, 275 , 276 , 309 ー 313 , 315 , 446 supervisor, 409 , 447 tox, 425 , 450 twine, 284 ー 286 , 449 unicode-slugify, 386 , 452 unipath, 59 ー 60 , 452 uWSGI, 408 , 411 ー 414 virtualenv, 15 , 16 , 20 , 27 ー 28 , 49 ー 51 , 256 , 257 , 271 , 273 , 274 , 287 , 288 , 446 , 454 , 455 virtualenvwrapper, 16 , 51 , 446 virtualenvwrapper-win , 446 493 PEP257, 313 PEPs pastebin, 440 Pandoc, 314 ー 315

ル x PEP 263 , 463 ー 464 PEP 328 , 7 PEP 427 , 285 ー 286 PEP 8 , 27 , 7 pickle, 342 ー 344 PIatform as a Service, 57 , 395 ー 403 PostgreSQJ. ,, 13 , 14 , 89 , 178 , 244 , 320 , 321 , 408 PowerSheII, 50 print(), 367 ー 368 Project TempIates, 21 ー 32 , 471772 cookiecutter grid, 21 cookiecutter-django, 21 , 28 ー 31 , 448 イ 94 requirements/, 56 requlrements. txt, 23 , 28 requirements, 56 ー 58 Remote Procedure CaIIs, 226 ー 227 Redis, 245 , 321 , 322 , 408709 README. rst, 23 , 32 Rate Limiting Your API, 227 ー 229 queries, 81 PYTHONPATH, 18 , 45 Pytho nAnywhere, 395703 pythona-unicode-compatible, 251 , 476 284 ー 286 , 288 , 313 ー 314 Python Package lndex, 265 , 270 , 279 ー 280 , Python 3 , 473 ー 476 PyPI, 271 , 275 , python package lndex Puppet, 414 ー 420 proxy models, 64 , 65 django-kevin, 31 , 448 django-herokuapp, 448 cookiecutter-pypackage, 282 cookiecutter-djangopackage, 282 , 287 REST APIs, 213 ー 230 reStructuredText, 276 , 309 ー 311 SaItStack, 414 SECRET KEY, 42 ー 43 , 48 ー 55 , 336 Secrets FiIe pattern, 53 ー 55 , 471 Security, 335 ー 362 allow-tags warning, 353 Checkups, 356 Clickjacking, 354 Code I 可 ection Attacks, 342 Cookie-based sessions, 343 ー 344 CSRF, 143 ー 144 , 341 CSRF and Jinja2, 206 defusedxml, 354 ー 355 django-admin-honeypot, 352 django. utils. html. remove-tag, 357 HSTS, 338 ー 340 HITPS, 336 ー 340 Mass Assignment Vulnerabilities, 350 pickle, 342 ー 343 Planning for Disaster, 357 ー 360 PyYAML security warning, 343 Secure the Django Admin, 351 ー 353 SecurityMiddIeware, 356 Settings Reference, 477 ー 478 SSL, 338 strip-tags, 384 TOTP, 355 Two-Factor Authentication, 355 Vulnerability page, 357 XML bombs, 354 ー 355 XSS, 341 ー 342 Zero-Day Attack, 360 select-related(), 180 , 318 Sentry, 372 , 448

settings, 26 , 41 ー 61 , 435 settings/base. py, 58 , settings/local. py, 45 , 46 , 48 settings/base. py, 52 signals, 373 ー 378 site—assets/, 27 slu ) , 195 , 385 ー 386 smoke test, 289 Sphinx, 275 SQJJite3, 13 , 14 SQLite3„ 424 sqlmigrate, 68 squashmigrations, 68 60 syntactic sugar, 115 STATICFILESDIRS, 27 TimeStampedModeI, 66 Testing, 91 , 289 ー 307 , 381 test coverage, 303 ー 306 stringffänvalid, 190 TEMPLATES OPTIONS 169 ー 193 templates, 23 , 26 , 31 , 58 , 60 , 130 , 133 , 135 , template tags, 12 , 195 , 197 ー 200 , 297 Upstream Caches, 324 unit tests, 291 unicode(), 253 Unicode, 251 , 383 , 463 , 467 ー 468 , 476 twoscoops-project, 35 Two Scoops Academy, 457 ー 458 , 460 Twelve Factor App, 471 ー 472 MyS ( , , 94 ATOMIC-REQUESTS, 89 ー 92 Transactions, 89 ー 94 Tips for Creating Database Migrations, 67 ル x URL namespaces, 101 ー 104 URLConfs, 23 , 26 , 96 ー 104 , 109 , 190 , 257 , 281 , 389 User model, 261 ー 267 Uti1ity ModuIes, 38 381 uWSGI, 411 ー 412 Vagrant, 19 ー 20 validation, 14 , 139 ー 168 VaniIIa S teak, 122 Varnish, 324 , 408 Virtua1Box, 20 wheel, 285 ー 286 , 288 Windows, 14 , 16 , 19 , 28 , 50 , 233 , 315 , 371 , 412 , 454 WSGI, 26 , 323 , 411714 WSGI Application Servers, 411 ー 414 495 Zen of Python, 171 ー 173 , 200 YAML and PyYAML security warning, 343 YAML, 54 ー 55 , 213 , 336 , 343 , 389 , 392 ー 393 XML bombs, 354 XML, 54 ー 55 , 213 , 336 , 347 , 389 , 393 , 413

奥付

Two Scoops of Django: Best Practices for Dj ango 1.8 FIhird Edition, 2015 ー 09 ー 02 Danie1 Roy Greenfeld and Audrey Roy Greenfe1d Copyright @ 2013 ー 2015 Daniel Roy Greenfeld, Audrey ROY Greenfeld, and Two Scoops Press. AII rights reserved. "lhis book may not be reproduced in any form, ⅲ whole or ⅲ part, without written permission from the authors, except ⅲ the case Of brief quotations embodied ⅲ articles or revie 、 vs. Limit of Liabi1ity and l)isclaimer of Warranty: "lhe authors have used their best efforts ⅲ preparing this book, and the inform ation provided herein as is. " 1 石 e information provided is sold without warranty, either express 0 「 implied. Neither the authors nor Cartwhee1 Web will be held liable for 田リ damages to caused either directly or indirectly the contents of this book. Trademarks: Rather than indicating every occurrence of a trademarked name as such, this book uses the names only ⅲ an editorial fashion and to the benefit of the trademark owner with no intention of infringement of the trademark. First Printing, April 2015 For more information, visit https : //twoscoopspress . com.